package cn.bellychang.leetcode.question020;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author ChangLiang
 * @date 2021/1/27
 */
public class Solution2 {

    public boolean isValid(String s) {
        Deque<Character> stack = new ArrayDeque<>();

        char[] chars = s.toCharArray();
        for (char aChar : chars) {
            if (aChar=='{' || aChar=='[' || aChar=='(') {
                stack.push(aChar);
            } else {
                char pop;
                try {
                    pop = stack.pop();
                } catch (Exception e) {
                    // 如果栈为空 右括号比左括号多
                    return false;
                }
                if (aChar == '}' && pop == '{') {
                    continue;
                } else if (aChar == ']' && pop == '[') {
                    continue;
                } else if (aChar == ')' && pop == '(') {
                    continue;
                } else {
                    return false;
                }
            }
        }
        return stack.size() == 0;
    }
}
